package cn.pconline.officialclub.web.wap;

import cn.pconline.autoclub.config.SystemConfig;
import cn.pconline.autoclub.entity.Album;
import cn.pconline.autoclub.entity.Club;
import cn.pconline.autoclub.entity.DynaInfo;
import cn.pconline.autoclub.entity.DynaPraise;
import cn.pconline.autoclub.entity.DynaReply;
import cn.pconline.autoclub.entity.User;
import cn.pconline.autoclub.entity.UserDyna;
import cn.pconline.autoclub.service.AlbumService;
import cn.pconline.autoclub.service.ClubService;
import cn.pconline.autoclub.service.EffectiveDynaService;
import cn.pconline.autoclub.service.SubjectDynaService;
import cn.pconline.autoclub.service.UserService;
import cn.pconline.autoclub.util.DateUtils;
import cn.pconline.autoclub.util.EncodeUtils;
import cn.pconline.autoclub.util.Pager;
import cn.pconline.autoclub.util.WebUtils;
import cn.pconline.autoclub.util.dyna.CommentDynaUtils;
import cn.pconline.autoclub.web.UserAuth;
import cn.pconline.autoclub.web.wap.ActionKit;
import cn.pconline.officialclub.entity.OActivity;
import cn.pconline.officialclub.entity.OClub;
import cn.pconline.officialclub.entity.OClubDyna;
import cn.pconline.officialclub.service.OActivityService;
import cn.pconline.officialclub.service.OClubService;
import cn.pconline.officialclub.service.ODynaService;
import cn.pconline.officialclub.service.OMemberService;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 *
 * @author xulin
 */
@Controller
@RequestMapping(value = "/wap/brand/dyna")
public class ODynaAction {

    @Autowired
    private EffectiveDynaService dynaService;
    @Autowired
    private ODynaService oDynaService;
    @Autowired
    private UserAuth userAuth;
    @Autowired
    private OClubService oClubService;
    @Autowired
    private SystemConfig systemConfig;
    @Autowired
    private OMemberService oMemberService;
    @Autowired
    private OActivityService oActivityService;
    @Autowired
    private SubjectDynaService subjectDynaService;
    @Autowired
    private UserService userService;
    @Autowired
    private ClubService clubService;
    @Autowired
    private AlbumService albumService;
    protected static final Logger log = LoggerFactory.getLogger(ODynaAction.class);

    /**
     * 获取WAP版首页动态列表
     *
     * @param request
     * @param response
     */
    @ResponseBody
    @RequestMapping(value = "/getDynaListByClubId.do", method = RequestMethod.GET)
    public void getDynaListByClubId(HttpServletRequest request, HttpServletResponse response) {
        WebUtils.setEncoding(request, response);
        int pageNo = WebUtils.paramInt(request, "pageNo", 1);
        int pageSize = WebUtils.paramInt(request, "pageSize", 10, 5, 20);
        long oClubId = WebUtils.paramOClubId(request);
        int xssEncode = WebUtils.paramInt(request, "xssEncode", 2);
        int needToViewUrl = WebUtils.paramInt(request, "needToViewUrl", 0);
        User user = userAuth.getUser(request, response);
        Pager<DynaInfo> dynaPager = oDynaService.getDynaListByClubId(oClubId, pageNo, pageSize, ODynaService.ORDER_CREATE_DATE);
        dynaService.filterImages(dynaPager);
        JSONObject json = new JSONObject();
        JSONArray list = new JSONArray();
        if (dynaPager != null) {
            //批量获取点赞列表
             List<DynaPraise> praises = null;
             praises = dynaService.getPraiseList(user.getUid(), dynaPager.getResultList());

            for (DynaInfo i : dynaPager.getResultList()) {
                if (i.getType() == DynaInfo.TYPE_COMMENT || i.isTopic()) {
                    String templateId;
                    JSONObject obj = new JSONObject();
                    if (needToViewUrl == 1) {
                        obj.put("content", WebUtils.dynaSubjectContent(systemConfig.getWapRoot(), WebUtils.transformToBBSFace(CommentDynaUtils.appendUrlUBB(i.getContent())), i.getSubjectIds()));
                    } else {
                        obj.put("content", WebUtils.transformToBBSFace(i.getContent()));
                    }
                    if (i.getType() == DynaInfo.TYPE_ACTIVITY) {
                        OActivity a = oActivityService.findById(OActivity.class, i.getTargetId());
                        if (a == null) {
                            log.error("dirty data,targetId not correct :[dynaInfo:{}],[targetId(activityId):{}]", i.getTargetId());
                            continue;
                        }
                        obj.put("activityId", i.getTargetId());
                        obj.put("activityCover", a.getPicUrl160x120());
                        obj.put("activityTitle", a.getTitle());
                        obj.put("activityStartTime", DateUtils.format(a.getBeginDate()));
                        obj.put("activityEndTime", DateUtils.format(a.getEndDate()));
                        obj.put("activityExpiredTime", DateUtils.format(a.getSignupDate(), "yyyy-MM-dd HH:mm:ss"));
                        obj.put("activityPlace", a.getProvinceId() == 0 ? "线上" : a.getProvinceName() + a.getCityName());
                        obj.put("activityMoney", a.getMoney());
                        obj.put("activityMaxJoin", a.getMaxJoin());
                        templateId = "template-activityDyna";
                    } else if (i.getType() == DynaInfo.TYPE_COMMENT) {
                        if (!StringUtils.isBlank(i.getSubjectIds())) {
                            templateId = "template-subjectDyna";
                            obj.put("subjectCount", subjectDynaService.countSubjectDyna(i.getSubjectIds()));
                        } else {
                            templateId = "template-commentDyna";
                        }
                    } else if (i.getType() == DynaInfo.TYPE_QUESTION || i.getType() == DynaInfo.TYPE_TOPIC) {
                        obj.put("topicId", i.getTargetId());
                        obj.put("forumId", i.getForumId());
                        templateId = "template-topicDyna";
                        obj.put("title", EncodeUtils.encodeForHTML(i.getTitle(), xssEncode));
                        obj.put("content", WebUtils.transformNoBBSFaceThenLimit(i.getContent(), 120, xssEncode));
                        obj.put("isPick", i.getPick());
                        obj.put("petrol", i.getPetrol());
                        obj.put("isRecommend", i.getRecommend());
                    } else {
                        continue;
                    }
                    obj.put("type", i.getType());
                    obj.put("templateId", templateId);
                    obj.put("avatar", WebUtils.face(i.getCreateBy(), User.DEFAULT_AVATAR_SIZE));
                    obj.put("nickName", EncodeUtils.encodeForHTML(userService.findUser(i.getCreateBy()).getNickname(), xssEncode));
                    obj.put("userId", i.getCreateBy());
                    obj.put("dynaInfoId", i.getDynaInfoId());
                    obj.put("year", DateUtils.format(i.getCreateDate(), "yyyy"));
                    obj.put("createDate", DateUtils.format(i.getCreateDate(), "yyyy-MM-dd HH:mm:ss"));
                    obj.put("fmtCreateDate", DateUtils.format(i.getCreateDate(), "MM-dd HH:mm:ss"));
                    obj.put("praiseCount", i.getPraiseCount());
                    obj.put("postCount", i.getPostCount());
                    obj.put("images", dynaService.parseWapImagesJSON(i.getImages()));
                    obj.put("isPraise", false); //是否点过赞
                    if(user.getUid()>0 && praises!=null && !praises.isEmpty()){
                       for(DynaPraise dynaPraise : praises){
                           if(dynaPraise.getDynainfoId() == i.getDynaInfoId()){
                               obj.put("isPraise", true);
                           }
                       }
                    }
                    list.add(obj);
                }
            }
            ActionKit.putPagerMessage(json, dynaPager);
            json.put("data", list);
        }
        ActionKit.printSuccessMsg(response, json, "");
    }

    /**
     * 品牌车友会发说说
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/postDyna.do", method = RequestMethod.GET)
    public String post(HttpServletRequest request, HttpServletResponse response) {
        long oClubId = WebUtils.paramOClubId(request);
        OClub oClub = oClubService.findValidClub(oClubId);
        if (oClub == null) {
            return ActionKit.SNED_ERROR_404;
        }
        User user = userAuth.getUser(request, response);
        if (user.getUid() == 0) {
            String loginUrl = systemConfig.getUcWapRoot() + "/passport/login.jsp?return=" + systemConfig.getBrandClubWapRoot() + "/" + oClub.getUrl();
            ActionKit.sendLogin(loginUrl, response);
            return null;
        }
        request.setAttribute("oClub", oClub);
        return "template/official/wap/dyna/post";
    }

    /**
     * 品牌车友会动态详情
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/dynaDetail.do", method = RequestMethod.GET)
    public String dynaDetail(HttpServletRequest request, HttpServletResponse response) {
        long dynaInfoId = WebUtils.paramLong(request, "dynaInfoId", 0L);
        long oClubId = WebUtils.paramOClubId(request);
        OClub oClub = oClubService.findValidClub(oClubId);
        if (oClub == null) {
            return ActionKit.SNED_ERROR_404;
        }
        OClubDyna oClubDyna = oDynaService.findClubDyna(dynaInfoId, oClubId);
        if (oClubDyna == null || DynaInfo.isTopic(oClubDyna.getType())
                || oClubDyna.getStatus() == DynaInfo.STATUS_DELETE) {
            //帖子动态没有详情页
            return ActionKit.SNED_ERROR_404;
        }
        DynaInfo dynaInfo = dynaService.findDynaById(dynaInfoId, oClubDyna.getCreateDate());
        if (dynaInfo == null) {
            log.error("车友会动态索引表有脏数据[clubId,dynaInfoId][{},{}]，对应的动态不存在", oClubId, dynaInfoId);
            return ActionKit.SNED_ERROR_404;
        }
        dynaService.filterImages(dynaInfo);//过滤掉不合法的图片
        String content = dynaInfo.getContent();
        if(dynaInfo.getType() == DynaInfo.TYPE_COMMENT){
            content = (WebUtils.dynaSubjectContent(systemConfig.getWapRoot(), WebUtils.transformToBBSFace(CommentDynaUtils.appendUrlUBB(dynaInfo.getContent())), dynaInfo.getSubjectIds()));
        }
        User user = userAuth.getUser(request, response);
        request.setAttribute("clubId", oClubId);
        request.setAttribute("user", user);
        request.setAttribute("isLogin", user.getUid() > 0);
        request.setAttribute("isMember", user.getUid() > 0 && oMemberService.findCommonMember(user.getUid(), oClub.getoClubId()) != null);
        request.setAttribute("oClub", oClub);
        request.setAttribute("imagesLength", dynaInfo.getImages() == null ? 0 : dynaInfo.getImages().size());
        request.setAttribute("dynaInfo", dynaInfo);
        request.setAttribute("time", DateUtils.getFormatedTime(dynaInfo.getCreateAt()));
        DynaPraise dp = dynaService.findDynaPraise(user.getUid(), dynaInfoId);
        if (dp != null && dp.getStatus() == DynaPraise.STATUS_PRAISE) {
            request.setAttribute("isPraise", true);
        }
        Pager<DynaReply> listReply = dynaService.getReplyListByDynaInfoId(dynaInfoId, 1, ActionKit.DEF_PAGE_SIZE);
        request.setAttribute("listReply", listReply);
        request.setAttribute("content", content);
        return "/template/official/wap/dyna/detail";
    }

    /**
     * 品牌车友会动态详情
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/ucDynaDetail.do", method = RequestMethod.GET)
    public String ucDynaDetail(HttpServletRequest request, HttpServletResponse response) {
        long dynaInfoId = WebUtils.paramLong(request, "dynaInfoId", 0L);
        long userId = WebUtils.paramLong(request, "userId", 0L);
        UserDyna userDyna = dynaService.findUserDynaById(dynaInfoId, userId);
        if (userDyna == null || DynaInfo.isTopic(userDyna.getType())
                || userDyna.getStatus() == DynaInfo.STATUS_DELETE 
                || userDyna.getType() == DynaInfo.TYPE_ACTIVITY
                || userDyna.getType() == DynaInfo.TYPE_JOIN_ACTIVITY
                || userDyna.getType() == DynaInfo.TYPE_VOTE) {
            //加入活动|创建活动|帖子动态|投票 都没有详情页
            return ActionKit.SNED_ERROR_404;
        }
        DynaInfo dynaInfo = dynaService.findDynaById(dynaInfoId, userDyna.getCreateDate());
        if (dynaInfo == null) {
            log.error("车友会动态索引表有脏数据[userId,dynaInfoId][{},{}]，对应的动态不存在", userId, dynaInfoId);
            return ActionKit.SNED_ERROR_404;
        }
        dynaService.filterImages(dynaInfo);//过滤掉不合法的图片
        String content = dynaInfo.getContent();
        if (dynaInfo.getType() == DynaInfo.TYPE_PICTURE) {
            Album a = albumService.getAlbumById(dynaInfo.getTargetId());
            if (a == null) {
                log.error("dirty data,targetId not correct :[dynaInfo:{}],[clubId:{}],[targetId(albumId):{}]", dynaInfo.getDynaInfoId(), dynaInfo.getClubId(), dynaInfo.getTargetId());
                return ActionKit.SNED_ERROR_404;
            }
            request.setAttribute("album", a);
            request.setAttribute("pictureNum", dynaInfo.getPictureNum());
        } else if (dynaInfo.getType() == DynaInfo.TYPE_CREATE_CLUB || dynaInfo.getType() == DynaInfo.TYPE_JOIN_CLUB) {
            Club club = clubService.getClub(dynaInfo.getClubId());
            if (club == null) {
                log.error("dirty data,targetId not correct :[dynaInfo:{}],[clubId:{}],club not exists", dynaInfo.getDynaInfoId(), dynaInfo.getClubId());
                return ActionKit.SNED_ERROR_404;
            }
            request.setAttribute("club", club);
        }else if(dynaInfo.getType() == DynaInfo.TYPE_COMMENT){
            content = (WebUtils.dynaSubjectContent(systemConfig.getWapRoot(), WebUtils.transformToBBSFace(CommentDynaUtils.appendUrlUBB(dynaInfo.getContent())), dynaInfo.getSubjectIds()));
        }
        User user = userAuth.getUser(request, response);
        request.setAttribute("user", user);
        request.setAttribute("content", content);
        request.setAttribute("isLogin", user.getUid() > 0);
        request.setAttribute("imagesLength", dynaInfo.getImages() == null ? 0 : dynaInfo.getImages().size());
        request.setAttribute("dynaInfo", dynaInfo);
        request.setAttribute("time", DateUtils.getFormatedTime(dynaInfo.getCreateAt()));
        if (user.getUid() > 0) {
            DynaPraise dp = dynaService.findDynaPraise(user.getUid(), dynaInfoId);
            if (dp != null && dp.getStatus() == DynaPraise.STATUS_PRAISE) {
                request.setAttribute("isPraise", true);
            }
        }
        Pager<DynaReply> listReply = dynaService.getReplyListByDynaInfoId(dynaInfoId, 1, ActionKit.DEF_PAGE_SIZE);
        request.setAttribute("listReply", listReply);
        request.setAttribute("content", content);
        return "/template/official/wap/dyna/ucDetail";
    }

    /**
     * 动态回复列表接口 请求参数：dynaInfoId
     *
     * @param request
     * @param response
     */
    @ResponseBody
    @RequestMapping(value = "/getReplyList.do", method = RequestMethod.GET)
    public void getReplyList(HttpServletRequest request, HttpServletResponse response) {
        WebUtils.setEncoding(request, response);
        String callback = WebUtils.param(request, "callback", "");
        long dynaInfoId = WebUtils.paramLong(request, "dynaInfoId", 0L);
        int pageSize = WebUtils.paramInt(request, "pageSize", ActionKit.DEF_PAGE_SIZE, ActionKit.MIN_PAGE_SIZE, ActionKit.MAX_PAGE_SIZE);
        int pageNo = WebUtils.paramInt(request, "pageNo", 1);
        int isTransFace = WebUtils.paramInt(request, "isTransFace", 1);
        JSONObject obj = new JSONObject();
        JSONArray arr = new JSONArray();
        int pageCount = 0;
        int sourceAgent = 2;
        if (dynaInfoId != 0) {
            Pager<DynaReply> pager = dynaService.getReplyListByDynaInfoId(dynaInfoId, pageNo, pageSize);
            if (pager != null) {
                for (DynaReply info : pager.getResultList()) {
                    JSONObject o = new JSONObject();
                    o.put("userId", info.getCreateBy());
                    o.put("dynaInfoId", info.getDynaInfoId());
                    o.put("replyId", info.getDynaReplyId());
                    o.put("createDate", DateUtils.format(info.getCreateAt(), "yyyy-MM-dd"));
                    o.put("myIcon", WebUtils.face(info.getCreateBy(), 50));
                    o.put("myIconUrl", systemConfig.getUcWapRoot() + "/" + info.getCreateBy() + "/");
                    o.put("nickName", EncodeUtils.encodeForHTML(info.getCreateName()));
                    o.put("time", DateUtils.getFormatedTime(info.getCreateDate()));
                    o.put("des", isTransFace == 1 ? WebUtils.transformToBBSFace(cn.pconline.autoclub.util.EncodeUtils.encodeForHTML(info.getContent(), sourceAgent)) : cn.pconline.autoclub.util.EncodeUtils.encodeForHTML(info.getContent(), sourceAgent));
                    arr.add(o);
                }
            }
            ActionKit.putPagerMessage(obj, pager);
        }
        obj.put("data", arr);
        ActionKit.printSuccessMsg(response, obj, callback);
    }
}
